<?php
/**
 * mysql 操作类
 * @author 41412754@qq.com
 */
class mysql {
	
	private $app;
	private $config;
	private $request;
	
	private $sql;
	private $conn;
	public static $querys = array();
	
	/**
	 * 初始化方法
	 * @param $dbhost
	 * @param $dbuser
	 * @param $dbpass
	 * @param $dbname
	 * @param $charset
	 */
	public function __construct( $dbhost = '', $dbuser = '', $dbpass = '', $dbname = '', $charset = 'utf8' )
	{
		$this->app = &$GLOBALS['app'];
		$this->config = &$this->app->config;
		$this->request = &$_REQUEST;
		
		if ( $dbhost ) return $this->connect( $dbhost, $dbuser, $dbpass, $dbname, $charset );
	}
	
	/**
	 * 关闭链接
	 */
	public function __destruct()
	{
		if ( is_object( $this->conn ) ) mysql_close( $this->conn );
	}
	
	/**
	 * 连接数据库
	 * @param $dbhost
	 * @param $dbuser
	 * @param $dbpass
	 * @param $dbname
	 * @param $charset
	 */
	public function connect( $dbhost, $dbuser, $dbpass, $dbname, $charset = 'utf8' )
	{
		$this->conn = mysql_connect( $dbhost, $dbuser, $dbpass, true ) or trigger_error( "Can't connect MySQL server $dbhost!" );
		if ( mysql_select_db( $dbname, $this->conn ) === false ) trigger_error( "Can't select MySQL database $dbname!" );
		mysql_query( "SET character_set_connection={$charset}, character_set_results={$charset}, character_set_client=binary", $this->conn );
		mysql_query( "SET sql_mode=''", $this->conn );
		return $this->conn;
	}
	
	/**
	 * 执行SQL语句
	 * @param $sql
	 */
	public function query( $sql = null )
	{
		if ( $sql == null ) $sql = $this->sql;
		
		self::$querys[] = $sql;
		$query = mysql_query( $sql, $this->conn );
		if ( ! $query && $this->config->debug ) trigger_error( '<pre style="border:1px solid #F00; padding:10px;">' . $sql . '</pre>' . mysql_error( $this->conn ) );
		else return $query;
	}
	
	/**
	 * 获取多条记录
	 * @param $sql
	 */
	public function getAll( $sql = null )
	{
		if ( $sql === null ) $sql = $this->sql;
		
		$res = $this->query( $sql );
		$rows = array();
		while ( $row = mysql_fetch_assoc( $res ) )
			$rows[] = (object)$row;
		return $rows;
	}
	
	/**
	 * 获取一条记录
	 * @param $sql
	 */
	public function getRow( $sql = null )
	{
		if ( $sql === null ) $sql = $this->sql;
		
		$res = $this->query( $sql );
		$row = mysql_fetch_assoc( $res );
		if ( $row ) $row = (object)$row;
		return $row;
	}
	
	/**
	 * 获得一个值
	 * @param $sql
	 */
	public function getOne( $sql = null )
	{
		if ( $sql == null ) $sql = $this->sql;
		
		$res = $this->query( $sql );
		$row = mysql_fetch_row( $res );
		if ( $row ) return $row[0];
		else return false;
	}
	
	/**
	 * 获得一个字段
	 * @param $sql
	 */
	public function getColumn( $sql = null )
	{
		if ( $sql == null ) $sql = $this->sql;
		
		$res = $this->query( $sql );
		$column = array();
		while ( $row = mysql_fetch_row( $res ) )
			$column[] = $row[0];
		return $column;
	}
	
	/**
	 * 获取刚刚插入的ID
	 */
	public function insertId()
	{
		return mysql_insert_id( $this->conn );
	}
	
	/**
	 * 缓存SQL
	 * @param $sql
	 */
	public function sql( $sql )
	{
		$this->sql = $sql;
		return $this;
	}
	
	/**
	 * 构建SQL语句字段
	 * @param $data
	 * @param $type
	 */
	public function compose( $data, $type )
	{
		if ( ! is_array( $data ) ) $data = (array)$data;
		if ( count( $data ) === 0 ) return false;
		switch ( $type )
		{
			case 'update' :
				foreach ( $data as $key => $val )
				{
					$val = mysql_real_escape_string( $val );
					$return[] = "`$key`='$val'";
				}
				$return = implode( ',', $return );
				break;
			
			case 'insert' :
				$fields = array();
				$values = array();
				foreach ( $data as $key => $val )
				{
					$fields[] = $key;
					$values[] = $val;
				}
				$return['fields'] = implode( ',', $fields );
				$return['values'] = implode( '\',\'', $values );
				$return = "({$return['fields']}) values ('{$return['values']}')";
				break;
		}
		return $return;
	}
	
	/**
	 * 自动分页
	 * @param $numPerPage 可选
	 */
	public function cutPage( $numPerPage = null )
	{
		/* 自动生成获取记录数的SQL */
		$sql = $this->sql;
		$pos = stripos( $sql, 'from ' ) - 6;
		$sql = substr_replace( $sql, ' count(*) ', 6, $pos );
		
		$pos = stripos( $sql, 'order by' );
		if ( $pos !== false ) $sql = substr_replace( $sql, '', $pos );
		
		$this->pageSQL = $sql;
		
		/* 分页 */
		$pageNum = $this->request['pageNum'];
		$pageNum = ($pageNum && ($pageNum > 1)) ? $pageNum : '1';
		$this->page->pageNum = $pageNum;
		if ( ! $numPerPage ) $numPerPage = $this->request['numPerPage'];
		if ( ! $numPerPage ) $numPerPage = 20;
		$this->page->numPerPage = $numPerPage;
		$this->page->total = $this->getOne( $sql );
		$limit = " limit " . ($pageNum - 1) * $numPerPage . ", {$numPerPage}";
		$this->sql .= $limit;
		
		return $this;
	}
	
	/**
	 * 输出SQL
	 * @param $exit
	 */
	public function printSQL( $exit = false )
	{
		echo "<br /><pre style=\"border:1px solid #ccc; padding:10px;\">{$this->sql}</pre><br />";
		if ( $exit ) exit();
		return $this;
	}
	
	/**
	 * 输出分页SQL
	 * @param $exit
	 */
	public function printPageSQL( $exit = true )
	{
		echo "<br /><pre style=\"border:1px solid #ccc; padding:10px;\">{$this->pageSQL}</pre><br />";
		if ( $exit ) exit();
	}
}
